package com.example.demo.controller;

import com.example.demo.db.MockDB;
import com.example.demo.pojo.ClientInfoVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
public class SsoServerController {
  @RequestMapping("/checkLogin")
  public String toLogin(String redirectUrl, HttpSession session, Model model, RedirectAttributes redirectAttributes) {
    //判断用户是否登录，就是判断是否拥有全局会话，token
    if (session.getAttribute("token") == null) {
      //没有全局会话，去登录界面
      model.addAttribute("redirectUrl", redirectUrl);
      return "login";
    } else {
      //存在全局会话，跳转到原来的地方
      String token = (String) session.getAttribute("token");
      redirectAttributes.addAttribute("token", token);
      return "redirect:" + redirectUrl;
    }
  }

  @RequestMapping("/login")
  public String login(String username, String password, String redirectUrl, HttpSession session, Model model) {
    if (username.equals("ykl") && password.equals("456")) {
      //1.给用户创建一个token令牌，唯一，保存到数据库 【现在用数据结构模拟一个数据库=>MockDB】
      String token = UUID.randomUUID().toString();
      //2.保存到数据库
      MockDB.T_TOKEN.add(token);
      //3.在服务器里保存会话信息，全局会话
      session.setAttribute("token", token);
      //4.将token发给客户端
      model.addAttribute("token", token);
      return "redirect:" + redirectUrl;//从哪里来回到那里去
    }
    //登录不成功
    model.addAttribute("redirectUrl", redirectUrl);
    return "login";
  }

  //验证token是否通过
  @RequestMapping("/verify")
  @ResponseBody
  public String verify(String token, String clientUrl, String jsessionId) {
    if (MockDB.T_TOKEN.contains(token)) {
      //保存用户的登出和session信息
      List<ClientInfoVo> clientInfoVoList = MockDB.T_CLIENT_INFO.get(token);
      if (clientInfoVoList == null) {//第一次一定是空的
        clientInfoVoList = new ArrayList<ClientInfoVo>();
    //将用户信息放入模拟数据库中
        MockDB.T_CLIENT_INFO.put(token, clientInfoVoList);
      }
      ClientInfoVo clientInfoVo = new ClientInfoVo();
      clientInfoVo.setClientUrl(clientUrl);
      clientInfoVo.setJsessionId(jsessionId);
      clientInfoVoList.add(clientInfoVo);
      return "true";
    }
    return "false";
  }


  //注销请求
  @RequestMapping("/logOut")
  public String logout(HttpSession session) {
    session.invalidate();
    //通知tb和tm销毁session,用session监听器实现
    return "login";
  }
}
